package com.project.app.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;

import com.hengyi.baseandroidcore.base.XBaseActivity;
import com.hengyi.baseandroidcore.listener.FileDownloadListener;
import com.hengyi.baseandroidcore.statusbar.StatusBarCompat;
import com.hengyi.baseandroidcore.update.AppUpdateManager;
import com.hengyi.baseandroidcore.update.UpdateBean;
import com.hengyi.baseandroidcore.utils.ColorUtils;
import com.hengyi.baseandroidcore.utils.CommonUtils;
import com.hengyi.baseandroidcore.utils.GsonUtils;
import com.hengyi.baseandroidcore.utils.NetworkUtils;
import com.hengyi.baseandroidcore.xutils.AppUtils;
import com.hengyi.baseandroidcore.xutils.LogUtils;
import com.hengyi.baseandroidcore.xutils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.project.app.R;
import com.project.app.dialog.ConfirmDialog;
import com.project.app.model.CheckVersionResultVo;
import com.project.app.model.CheckVersionVo;
import com.project.app.utils.api.LoginAPIConstant;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by Fanhua on 2017/10/10.
 * 由于ButterKnife不能再lib中bind。所以必须继承BaseActivity进行二次封装
 */

public abstract class MyXBaseActivity extends XBaseActivity {
    private static final String TAG = "MyXBaseActivity";
    private Unbinder unbind = null;
    private static Boolean isExit = false;
    ConfirmDialog confirmDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        unbind = ButterKnife.bind(this);
        boolean status = NetworkUtils.isNetworkConnected(this);
        if (!status) {
            ToastUtils.showShort("您的网络状况有问题，请检查网络~~~");
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor(ColorUtils.changeColor(this, R.color.main_color)));
    }

    /**
     * 再次按下返回键退出
     */
    public void exitBy2Click() {
        Timer tExit;
        if (isExit == false) {
            isExit = true; // 准备退出
            ToastUtils.showShort("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            CommonUtils.kill();
        }
    }

    /**
     * 检查更新
     */
    public void checkUpdateByServer() {
        //数据
        String localversion = AppUtils.getAppVersionName();
        OkGo.<String>get(LoginAPIConstant.CHECKVERSION)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .params("version", localversion)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String res = response.body();
                        CheckVersionResultVo resultVo = GsonUtils.parseJsonWithGson(res, CheckVersionResultVo.class);
                        if (resultVo.getCode() == 200) {
                            if (resultVo.getData() != null) {
                                CheckVersionVo data = resultVo.getData();
                                checkUpdate(data.getTitle(), data.getDescription(), data.getAppDownurl(), data.isForce(), data.getAppVersion());
                            }
                        } else {
                            ToastUtils.showShort(resultVo.getMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.showShort("服务器开小差了~~");
                    }
                });


    }

    private void checkUpdate(String title, String description, String download_url, boolean force, String newversion) {
        UpdateBean updateBean = new UpdateBean();
        updateBean.setDescription(description);
        updateBean.setDownloadUrl(download_url);
        updateBean.setForce(force);//是否强制更新 或 静默安装
        updateBean.setAuthority("com.youyou.pos");//兼容安卓7.0 安装
        updateBean.setMd5Code(null);
        updateBean.setVersionName(newversion);
        updateBean.setTitle(title);
        AppUpdateManager appUpdateManager = AppUpdateManager.getInstance();
        appUpdateManager.checkUpdate(updateBean,2,false, this);
        appUpdateManager.setAppUpdateListener(new FileDownloadListener() {
            @Override
            public void downloadProgressBar(final String progress, int i, String speed) {
                Log.d(TAG, "进度条：" + progress + "   下载速度：" + speed);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                        Message message = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("progress", progress);// 将服务器返回的订单号传到Bundle中，，再通过handler传出
                        message.setData(bundle);
                        message.what = 0;
                        mHandler.sendMessage(message);
                    }
                }).start();
            }

            @Override
            public void downloadSuccess(File app_path) {
                Log.d(TAG, "下载成功    路径如下：" + app_path.getAbsolutePath());
            }

            @Override
            public void downloadStart() {
                Log.d(TAG, "下载开始");
                confirmDialog = new ConfirmDialog(MyXBaseActivity.this);
                confirmDialog.setCancelable(false);
                confirmDialog.show();
            }

            @Override
            public void downloadError(String message) {
                Log.d(TAG, "下载错误");
                confirmDialog.dismiss();
            }

            @Override
            public void downloadFinish() {
                Log.d(TAG, "下载结束");
                confirmDialog.dismiss();
            }

            @Override
            public void cancelDownload() {
                Log.d(TAG, "取消下载");
                confirmDialog.dismiss();
            }

            @Override
            public void NoUpdate() {
                Log.d(TAG, "没有更新");
            }
        });
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 0) {
                Bundle bundle = msg.getData();
                String progress = bundle.getString("progress");// 这里的orderid是一个全局变量
                Double num = Double.parseDouble(progress);
                int intnum = num.intValue();
                LogUtils.d(TAG, intnum);
                confirmDialog.setNumberProgress(intnum);
            }
        }
    };

    @Override
    public int setBaseContentView() {
        return setContentView();
    }

    public abstract int setContentView();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind.unbind();
    }
}
